<template>
	<div class="home">
		<!-- 项目筛选 -->
		<van-tabs type="card" @click="projectChange" color="#87A2FF" custom-class="tabs">
			<van-tab title="项目1"></van-tab>
			<van-tab title="项目2"></van-tab>
		</van-tabs>
		<div class="calendar">
			<!-- 日历头部：包含年份、月份切换 -->
			<div class="calendar-header">
				<div class="calendar-month-year">
					{{capitalizeChinese}}月 {{ currentYear }}
				</div>
				<button class="nav-btn" @click="prevYear">«</button>
				<button class="nav-btn" @click="prevMonth">《</button>
				<button class="nav-btn" @click="nextMonth">》</button>
				<button class="nav-btn" @click="nextYear">»</button>
			</div>

			<!-- 星期标题 -->
			<div class="week-days">
				<div v-for="(day, index) in weekDays" :key="index" class="week-day">
					{{ day }}
				</div>
			</div>

			<!-- 日历主体，按照周分组，每行固定7个单元格 -->
			<div class="days-grid">
				<div v-for="(week, weekIndex) in calendarData" :key="weekIndex" class="week-row">
					<div v-for="(dayItem, dayIndex) in week" :key="dayIndex" class="day-item" :class="{
	    marked: isMarked(dayItem),
	    'other-month': !dayItem.currentMonth,
	    'non-clickable': !dayItem.currentMonth
	  }" @click="handleClick(dayItem)">
						<!-- 包裹日期数字和装饰的容器，用于定位 -->
						<div class="day-content" v-if="dayItem.date">
							<text class="day-number">{{ dayItem.date.getDate() }}</text>
							<!-- 左上角红色感叹号 -->
							<text class="exclamation" v-if="dayItem.exclamation">!</text>
							<!-- 底部小圆点 -->
							<div class="dot" v-if="dayItem.dot"></div>
						</div>
					</div>
				</div>
			</div>

		</div>
		<!-- 从根节点开始构造整个树结构 -->
		<div class="task">
			<TreeItem :item="treeData" />
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue';
	import {
		onPullDownRefresh
	} from "@dcloudio/uni-app"
	const projectChange = (event) => {
		const {
			index
		} = event.detail;
		console.log(index)
	}

	// 设置允许的最小和最大日期（根据需要修改）
	const minDate = new Date("2020-01-01");
	const maxDate = new Date("2030-12-31");

	// 当前显示的日期状态，初始为今天所在月份
	const currentDate = ref(new Date());
	const currentYear = computed(() => currentDate.value.getFullYear());
	const currentMonth = computed(() => currentDate.value.getMonth() + 1);
	const weekDays = ["日", "一", "二", "三", "四", "五", "六"];

	/*
	  格式化日期为 "YYYY-MM-DD" 字符串格式
	*/
	const formatDate = (date) => {
		const y = date.getFullYear();
		const m = date.getMonth() + 1;
		const d = date.getDate();
		return `${y}-${m < 10 ? '0' + m : m}-${d < 10 ? '0' + d : d}`;
	}

	/*
	  默认高亮当天：将今天格式化后存入 markedDay
	*/
	const markedDay = ref(formatDate(new Date()));


	const markDay = (dayItem) => {
		if (dayItem.date) {
			markedDay.value = formatDate(dayItem.date);
		}
	}

	const isMarked = (dayItem) => {
		if (!dayItem.date) return false;
		return formatDate(dayItem.date) === markedDay.value;
	}

	/*
	  示例条件函数 conditionA:  
	  此处示例条件为当日期的“日”数等于15时返回 true  
	  你可根据业务需求自定义此判断逻辑
	*/
	const conditionA = (date) => {
		return date.getDate() === 15;
	}

	/*
	  生成日历数据：  
	  - 根据本月第一天所在星期数，将上月尾部的日期补全  
	  - 填充本月所有日期  
	  - 如果最后一行不足7个，用下月的日期补全  
	  同时判断每个日期是否满足 conditionA，满足则设置 dot 和 exclamation 为 true
	*/
	const calendarData = computed(() => {
		const year = currentDate.value.getFullYear();
		const month = currentDate.value.getMonth(); // 月份范围 0~11
		const firstDay = new Date(year, month, 1);
		const startWeekDay = firstDay.getDay();
		const daysInMonth = new Date(year, month + 1, 0).getDate();

		const weeks = [];
		let week = [];

		// 补全上个月尾部日期（如果第一天不是周日）
		if (startWeekDay > 0) {
			const prevMonthDays = new Date(year, month, 0).getDate();
			for (let i = 0; i < startWeekDay; i++) {
				const dateObj = new Date(year, month - 1, prevMonthDays - startWeekDay + i + 1);
				const cell = {
					date: dateObj,
					currentMonth: false,
					dot: false,
					exclamation: false
				};
				if (conditionA(dateObj)) {
					cell.dot = true;
					cell.exclamation = true;
				}
				week.push(cell);
			}
		}

		// 填充当前月日期
		for (let day = 1; day <= daysInMonth; day++) {
			const dateObj = new Date(year, month, day);
			const cell = {
				date: dateObj,
				currentMonth: true,
				dot: false,
				exclamation: false
			};
			if (conditionA(dateObj)) {
				cell.dot = true;
				cell.exclamation = true;
			}
			week.push(cell);
			if (week.length === 7) {
				weeks.push(week);
				week = [];
			}
		}

		// 补全下个月开始的日期（如果最后一行不足7个）
		if (week.length > 0) {
			let nextMonthDay = 1;
			while (week.length < 7) {
				const dateObj = new Date(year, month + 1, nextMonthDay);
				const cell = {
					date: dateObj,
					currentMonth: false,
					dot: false,
					exclamation: false
				};
				if (conditionA(dateObj)) {
					cell.dot = true;
					cell.exclamation = true;
				}
				week.push(cell);
				nextMonthDay++;
			}
			weeks.push(week);
		}
		return weeks;
	});

	/*
	  切换月份和年份操作：  
	  每次更新 currentDate 前先构造新日期，再判断新日期是否在 [minDate, maxDate] 范围内
	*/
	const prevMonth = () => {
		const year = currentDate.value.getFullYear();
		const month = currentDate.value.getMonth();
		let newMonth = month - 1;
		let newYear = year;
		if (newMonth < 0) {
			newMonth = 11;
			newYear -= 1;
		}
		const newDate = new Date(newYear, newMonth, 1);
		if (newDate < minDate) {
			uni.showToast({
				title: "已超出日期最小范围",
				icon: "none"
			});
			return;
		}
		currentDate.value = newDate;
	}

	const nextMonth = () => {
		const year = currentDate.value.getFullYear();
		const month = currentDate.value.getMonth();
		let newMonth = month + 1;
		let newYear = year;
		if (newMonth > 11) {
			newMonth = 0;
			newYear += 1;
		}
		const newDate = new Date(newYear, newMonth, 1);
		if (newDate > maxDate) {
			uni.showToast({
				title: "已超出日期最大范围",
				icon: "none"
			});
			return;
		}
		currentDate.value = newDate;
	}

	const prevYear = () => {
		const year = currentDate.value.getFullYear();
		const month = currentDate.value.getMonth();
		const newDate = new Date(year - 1, month, 1);
		if (newDate < minDate) {
			uni.showToast({
				title: "已超出日期最小范围",
				icon: "none"
			});
			return;
		}
		currentDate.value = newDate;
	}

	const nextYear = () => {
		const year = currentDate.value.getFullYear();
		const month = currentDate.value.getMonth();
		const newDate = new Date(year + 1, month, 1);
		if (newDate > maxDate) {
			uni.showToast({
				title: "已超出日期最大范围",
				icon: "none"
			});
			return;
		}
		currentDate.value = newDate;
	}
	const capitalizeChinese = computed(() => {
		const monthMap = {
			1: '一',
			2: '二',
			3: '三',
			4: '四',
			5: '五',
			6: '六',
			7: '七',
			8: '八',
			9: '九',
			10: '十',
			11: '十一',
			12: '十二'
		};
		return monthMap[currentMonth.value];
	})
	/*
	  点击处理函数：  
	  只有当当前单元属于当前月（即 dayItem.currentMonth === true）时才执行 markDay
	*/
	const handleClick = (dayItem) => {
		if (dayItem.currentMonth) {
			markDay(dayItem);
		}
		console.log('单个日期选择')
	}

	// 构造示例树数据，每个节点包含 id、name、time、status、expanded 和 children 字段
	const treeData = ref({
		id: 1,
		title: "定植",
		status: "进行中",
		time: "2025-04-28",
		expanded: true, // 根节点默认展开
		children: [{
				id: 2,
				title: "加量施肥",
				status: "进行中",
				time: "2025-04-28",
				expanded: false,
				children: []
			},
			{
				id: 3,
				title: "栽苗",
				status: "进行中",
				time: "2025-04-28",
				expanded: false,
				children: [{
						id: 4,
						title: "栽蚕豆苗",
						status: "进行中",
						time: "2025-04-28",
						expanded: false,
						children: []
					},
					{
						id: 5,
						title: "栽玉米苗2",
						status: "延迟",
						time: "2025-04-28",
						expanded: false,
						children: []
					}
				]
			}
		]
	});
	// 下拉刷新
	onPullDownRefresh(() => {
	setTimeout(() => {
			uni.stopPullDownRefresh();
	},1000)
	})
</script>

<style scoped lang="scss">
	.home {
		padding: $uni-space-default-20;

		.calendar {
			border: 1px solid $uni-border-color;
			padding: $uni-space-default-20;
			border-radius: $uni-border-radius-lg;
			margin-top: $uni-space-default-40;

			/* 日历头部 */
			.calendar-header {
				display: flex;
				justify-content: space-around;
				align-items: center;
				margin-bottom: $uni-space-default-20;
			}

			.nav-btn {
				background-color: transparent;
				border: none;
				font-size: $uni-font-size-26-rpx;
			}

			.calendar-month-year {
				font-size: $uni-font-size-30-rpx;
				margin: 0 $uni-space-default-20;
			}

			/* 星期标题 */
			.week-days {
				display: flex;
				justify-content: space-around;
				margin-bottom: 10rpx;
				font-weight: bold;
				font-size: $uni-font-size-26-rpx ;
			}

			.week-day {
				width: 14.28%;
				text-align: center;
			}

			/* 日历主体 */
			.days-grid {}

			.week-row {
				display: flex;
			}

			.day-item {
				width: 14.28%;
				height: 80rpx;
				text-align: center;
				line-height: 80rpx;
				box-sizing: border-box;
				position: relative;
				font-size: $uni-font-size-26-rpx ;
				color: $uni-text-color;
				/* 为绝对定位的子元素提供参考 */
			}

			/* 高亮选中的当前月日期 */
			.day-item.marked {
				background-color: $uni-bg-color-default;
				color: #fff;
				border-radius: $uni-border-radius-lg;
			}

			/* 非当前月的日期样式 */
			.day-item.other-month {
				color: $uni-text-color-disable;
				background: #f9f9f9;
			}

			/* 禁用补全的日期点击 */
			.day-item.non-clickable {
				pointer-events: none;
			}

			/* 包裹日期数字及装饰的容器 */
			.day-content {
				position: relative;
				width: 100%;
				height: 100%;

			}

			/* 日期数字样式 */
			.day-number {
				position: relative;
				z-index: 1;
			}

			/* 左上角红色感叹号 */
			.exclamation {
				position: absolute;
				top: 4rpx;
				left: 4rpx;
				font-size: 20rpx;
				color: red;
				z-index: 2;
				border: 2px solid red;
				border-radius: 50%;
				width: 26rpx;
				height: 26rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-weight: bold;
			}

			/* 底部小圆点 */
			.dot {
				position: absolute;
				bottom: 4rpx;
				left: 50%;
				transform: translateX(-50%);
				width: 12rpx;
				height: 12rpx;
				background-color: #333;
				border-radius: 50%;
				z-index: 2;
			}
		}

		.task {
			margin-top: $uni-space-default-40;
			border: 1px solid $uni-border-color;
			border-radius: $uni-border-radius-lg;
			padding: $uni-space-default-20;

		}
	}
</style>